package cn.com.open.itembank.redis;

import cn.com.open.itembank.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by lucky on 2018/1/9.
 */

@Component
public class RedisConfig {
    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 添加
     *
     * @param key    key
     * @param doamin 对象
     * @param expire 过期时间(单位:秒),传入 -1 时表示不设置过期时间
     */
    public void set(String key, Object doamin, long expire) {
        boolean bExistent = this.stringRedisTemplate.hasKey(key);
        if (bExistent) {
            logger.info("this key is bExistent!");
        } else {
            String value = JsonUtil.getJson(doamin);
            ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
            ops.set(key, value, expire, TimeUnit.SECONDS);
        }
    }

    /**
     * Get string.
     *
     * @param key the key
     * @return the string
     */
    public String get(String key) {
        return this.stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * Gets object.
     *
     * @param <T>  the type parameter
     * @param key  the key
     * @param type the type
     * @return the object
     */
    public <T> T getObject(String key, Class<T> type) {
        String jsonString = get(key);
        return JsonUtil.fromJson(jsonString, type);
    }

    /**
     * 删除
     *
     * @param key 传入key的名称
     */
    public void del(String key) {
        this.stringRedisTemplate.delete(key);
    }


    /**
     * 判断key是否存在redis中
     *
     * @param key 传入key的名称
     * @return boolean
     */
    public boolean isKeyExists(String key) {
        return stringRedisTemplate.hasKey(key);
    }
}